package com.coflxl.web.config;

import com.coflxl.common.handler.ApiExceptionHandler;
import com.coflxl.common.model.ResultCode;
import com.coflxl.common.model.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;

/**
 * 全局异常处理
 */
@ControllerAdvice
@RestController
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 处理自定义的业务异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ApiExceptionHandler.class)
    public ApiResult apiExceptionHandler(ApiExceptionHandler e) {
        log.error("发生业务异常！原因是：{}", e.getErrorMsg());
        return ApiResult.FAILURE(e.getErrorCode(), e.getErrorMsg());
    }


    /**
     * 处理空指针的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    public ApiResult exceptionHandler(NullPointerException e) {
        log.error("发生空指针异常！原因是:", e);
        return ApiResult.FAILURE(ResultCode.PARAM_ERROR);
    }

    /**
     * 处理文件找不到的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = FileNotFoundException.class)
    public ApiResult exceptionHandler(FileNotFoundException e) {
        log.error("发生文件找不到异常！原因是:", e);
        return ApiResult.FAILURE(ResultCode.NOT_FOUND);
    }

    /**
     * 索引越界的异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = ArrayIndexOutOfBoundsException.class)
    public ApiResult exceptionHandler(ArrayIndexOutOfBoundsException e) {
        log.error("发生数组索引越界异常！原因是:", e);
        return ApiResult.FAILURE(ResultCode.SERVER_ERROR.code(), "数组越界，请检查数据");
    }

    /**
     * 处理其他异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ApiResult exceptionHandler(Exception e, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        log.error("发生未知异常！原因是:", e);
        return ApiResult.FAILURE(ResultCode.SERVER_ERROR);
    }

}